package com.example.waimaiandroid;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.waimai.HttpUtil.MyPost;
import com.example.waimai.context.UserInfoContext;
import com.example.waimai.pojo.Food;
import com.example.waimai.pojo.FoodAndFoodType;
import com.example.waimai.pojo.FoodType;
import com.example.waimai.pojo.Orders;
import com.example.waimai.pojo.Store;
import com.example.waimai.pojo.StoreAddress;
import com.example.waimai.util.MyThreadPool;
import com.example.waimaiandroid.billing.BillingActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import se.emilsjolander.stickylistheaders.StickyListHeadersListView;

public class diancanActivity extends AppCompatActivity {

    Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 1:
                    // 用户id
                    Orders order = (Orders) msg.obj;
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("Order",order);
                    bundle.putString("StoreName",store.getStoreName());
                    intent.putExtras(bundle);
                    intent.setComponent(new ComponentName(getActivity(), BillingActivity.class));
                    getActivity().startActivity(intent);
                    break;
            }
        }
    };

    private Store store;

    ImageView mBg;

    TextView mTitle,mSubTitle;

    LinearLayout mLists;
    FrameLayout.LayoutParams mListsParams;

    ListView mLeftListView;
    LeftAdapter mLeftAdapter;
    StickyListHeadersListView mRightListView;
    RightAdapter mRightAdapter;

    List<FoodType> foodTypes;  // 数据
    List<Food> foods; // 数据
    List<Food> goodsCart = new ArrayList<>();

    // 总金额
    private float totalPrice = 0;
    // 总数量
    private int totalNum = 0;

    /*
    * 购物车实现
    * */
    private LinearLayout mWindow; // 购物车页面 控制显示和不显示
    //private View mView; // 控制显示和不显示
    private TextView mClear ; // 清空
    private TextView mTotalPrice; // 总价格
    private TextView mBilling; // 结算
    private ImageView mCart;// 购物车图片
    private TextView mTvCount; // 商品总数
    private GoodsCartAdapter mGoodsCartAdapter;
    private ListView mListCart;
    private boolean isVisiable = false; // 是否显示？
    // listView  list_cart listietm_goods_cart


    private Activity getActivity(){
        return this;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diancan);


        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.argb(100,0,0,0));
        }

        initData();
        initViews();
    }

    private void initData() {

        // 生成数据
        // 好像也没有必要生成， Intent传入数据
        Bundle extras = this.getIntent().getExtras();
       foods = (List<Food>) extras.getSerializable("Foods");
       foodTypes = (List<FoodType>) extras.getSerializable("FoodTypes");
       store = (Store) extras.getSerializable("Store");
       goodsCart = new ArrayList<>();
    }

    private void initViews() {
        // 初始化 购物车
        //mView = findViewById(R.id.view);
        mWindow = findViewById(R.id.window);
        mClear = findViewById(R.id.clear);
        mTotalPrice = findViewById(R.id.price_main);
        mBilling = findViewById(R.id.billing);
        mCart = findViewById(R.id.cart);
        mTvCount = findViewById(R.id.tv_count);
        mListCart = findViewById(R.id.list_cart);
        mGoodsCartAdapter = new GoodsCartAdapter(this,goodsCart,mGoodsCarAdapterCallback);
        mListCart.setAdapter(mGoodsCartAdapter);

        // 初始化 店铺详细页
        mBg = (ImageView) findViewById(R.id.bg); // 背景图片 上方的背景
        //mBg.setImageBitmap(Tools.blurBitmap(this, BitmapFactory.decodeResource(this.getResources(),R.drawable.bg),20));
        Glide.with(this).load(store.getStoreImage()).into(mBg);
        mTitle = (TextView) findViewById(R.id.title); // 上方的标题
        mSubTitle = (TextView) findViewById(R.id.subtitle);
        mTitle.setText(store.getStoreName());
        mSubTitle.setText(store.getStoreName());

        mLists = (LinearLayout) findViewById(R.id.lists); //主体内容布局
        mListsParams = (FrameLayout.LayoutParams) mLists.getLayoutParams();

        mLeftListView = (ListView) findViewById(R.id.left_list); //  菜品类型
        mLeftAdapter = new LeftAdapter(this,foodTypes); // 初始化适配器
        mLeftListView.setAdapter(mLeftAdapter); // ListView


        mRightListView = (StickyListHeadersListView) findViewById(R.id.right_list); // 菜品
        mRightAdapter = new RightAdapter(this,foods,mCallback);
        mRightListView.setAdapter(mRightAdapter);

        mLeftListView.setOnTouchListener(new ListParentOnTouchListener(mDelegate));
        mRightListView.setOnTouchListener(new ListParentOnTouchListener(mDelegate));

        mLeftListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { // 添加菜品类型的事件监听 选中菜品类型项
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if(isVisiable){
                    mWindow.setVisibility(View.GONE);
                    isVisiable = false;
                }else{
                    // 选中菜单项高亮
                    mLeftAdapter.updateSelected(i);
                    // 找到菜单类型的第一项
                    mRightListView.setSelection(getRightPosition(i));
                }

            }
        });

        mRightListView.setOnScrollListener(new AbsListView.OnScrollListener() { // 菜品滚动的事件监听
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
                try {
                    long cId = mRightAdapter.getHeaderId(firstVisibleItem);
                    mLeftAdapter.updateSelected(getLeftPosition(cId));

                } catch (Exception e) {

                }
            }
        });

        // 购物车监听器 设置
        mCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!isVisiable){
                    // 更新 ListView 视图
                    mGoodsCartAdapter.notifyDataSetChanged();
                    // 显示购物车视图
                    //mView.setVisibility(View.VISIBLE);
                    mWindow.setVisibility(View.VISIBLE);
                    isVisiable = true;
                }else{
                    // 关闭视图
                    //mView.setVisibility(View.GONE);
                    mWindow.setVisibility(View.GONE);
                    isVisiable = false;
                }

            }
        });

        // 结算 事件
        mBilling.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 首先判断一下是否有地址信息
                if(UserInfoContext.mUserAddress == null || UserInfoContext.mUserAddress.size() == 0){
                    Toast.makeText(diancanActivity.this,"你还未设置收货地址，请先添加收货地址！",Toast.LENGTH_SHORT).show();
                    return ;
                }
                /*生成订单*/
                Integer storeId = null;
                Orders order = new Orders();
                order.set_foodList(goodsCart);
                order.setTotalPrice(totalPrice);
                order.setStoreId(store.getId());
                order.setStore(store);
                // 获取一下店铺地址？
                MyThreadPool.doJob(new Runnable() {
                    @Override
                    public void run() {
                        order.setStoreAddress((StoreAddress) MyPost.doPost("getStoreAddress",store.getId()));
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = order;
                        handler.sendMessage(msg);
                    }
                });

            }
        });

    }

    // 根据菜单项获取其第一个菜品的位置
    private int getRightPosition(int leftPosition){
        int position = 0;
        // 获取 菜品类型名称
        Integer typeId = foodTypes.get(leftPosition).getId();
        // 获取到该菜单类型的第一个菜品
        for(int i=0;i<foods.size();i++){
            Integer tempTypeId = foods.get(i).getFoodTypeId();
            if(tempTypeId .equals(typeId)){
                position = i;
                break;
            }
        }
        return position;
    }

    //  根据菜单项Id找到菜单项的索引
    private int getLeftPosition(long cId){
        int position = 0;
        Integer ccid = (int)cId;
        for (int i = 0;i<foodTypes.size();i++){
            if (foodTypes.get(i).getId().equals(ccid)) {
                position = i;
                break;
            }
        }
        return position;
    }

    TouchDelegate mDelegate = new TouchDelegate() { //
        @Override
        void onTouchDone(View view,TouchOrientation orientation,float offset) {
            if (orientation == TouchOrientation.DOWN_2_UP) {//往上
                int topMargin = Tools.px2dip(diancanActivity.this,mListsParams.topMargin);
                int configToolBarHeight = Tools.px2dip(diancanActivity.this,getResources().getDimension(R.dimen.toolbar_height));
                float configToolBarHeightPx = getResources().getDimension(R.dimen.toolbar_height);
                float configTopMarginPx = getResources().getDimension(R.dimen.top_margin);
                if (topMargin > configToolBarHeight) {
                    ListParentOnTouchListener.SCROLL_ENABLE = false;
                    float top = (mListsParams.topMargin - offset);
                    if (top < configToolBarHeightPx) top = configToolBarHeightPx;
                    mListsParams.setMargins(mListsParams.leftMargin, (int) top, mListsParams.rightMargin, mListsParams.bottomMargin);
//                    mLists.requestLayout();
                    mLists.setLayoutParams(mListsParams);
                    float scale = top / configTopMarginPx;
                    mTitle.setAlpha(scale);
                    mSubTitle.setAlpha(1-scale);
                }else{
                    mTitle.setAlpha(0);
                    mSubTitle.setAlpha(1);
                    ListParentOnTouchListener.SCROLL_ENABLE = true;
                }
            }else if (orientation == TouchOrientation.UP_2_DOWN) {//往下
                int topMargin = Tools.px2dip(diancanActivity.this,mListsParams.topMargin);
                int configTopMargin = Tools.px2dip(diancanActivity.this,getResources().getDimension(R.dimen.top_margin));
                float configTopMarginPx = getResources().getDimension(R.dimen.top_margin);
                if (topMargin == configTopMargin) {
                    ListParentOnTouchListener.SCROLL_ENABLE = true;
                    mTitle.setAlpha(1);
                    mSubTitle.setAlpha(0);
                }else{
                    ListParentOnTouchListener.SCROLL_ENABLE = false;
                    float top = (mListsParams.topMargin + offset);
                    if (top > configTopMarginPx) top = configTopMarginPx;
                    mListsParams.setMargins(mListsParams.leftMargin, (int) top, mListsParams.rightMargin, mListsParams.bottomMargin);
//                    mLists.requestLayout();
                    mLists.setLayoutParams(mListsParams);
                    float scale = top / configTopMarginPx;
                    mTitle.setAlpha(scale);
                    mSubTitle.setAlpha(1-scale);
                }

            }
        }
    };

    //  菜品 监听事件 点菜或者删除
    RightAdapterCallback mCallback = new RightAdapterCallback() {
        @Override
        void onClickNumButton(int position, boolean isAdd) {
            if(isVisiable){
                mWindow.setVisibility(View.GONE);
                isVisiable = false;
            }else{
                int startNum = foods.get(position).getAddNums();
                // 更新菜品 数量数据
                foods.get(position).setAddNums(foods.get(position).getAddNums() + (isAdd ? 1 : -1));
                int endNum = foods.get(position).getAddNums();
                // 调用更新方法
                mRightAdapter.update(position,foods.get(position));
                // 同时菜品类型项也要进行更新 获取到当前菜品对应的菜单类型项
                int leftPosition = getLeftPosition(foods.get(position).getFoodTypeId());
                foodTypes.get(leftPosition).setAddNums(foodTypes.get(leftPosition).getAddNums() + (isAdd ? 1 : -1));
                mLeftAdapter.update(leftPosition,foodTypes.get(leftPosition));
                // 判断一下是否要加入到购物车中 或者从购物车中删除？
                // 不需要更新购物车视图 视图没有显示。
                if(isAdd){
                    // 添加操作
                    if(startNum == 0){ // 0 -> 1 说明购物车中没有该菜品，需要加入
                        goodsCart.add(foods.get(position));
                    }
                    updateTotalPrice(foods.get(position).getFoodPrice());
                }else{
                    // 删除操作
                    if(endNum == 0){
                        // 将该菜品从 购物车中删除
                        goodsCart.remove(foods.get(position));
                    }
                    updateTotalPrice(-foods.get(position).getFoodPrice());
                }
                updateTvCount(isAdd);
            }
        }
    };

    GoodsCartAdapterCallback mGoodsCarAdapterCallback = new GoodsCartAdapterCallback() {
        @Override
        public void onClickItem(int position,boolean isAdd) {
            // position 是购物车的中的   可以获取到 购物车中 food
            // 找 foods  和 goodsCart 的数据然后进行更新  更新页面
            Food food = goodsCart.get(position);
            int leftPosition = getLeftPosition(food.getFoodTypeId());
            if(isAdd){
                // 改变一下总金额
                // 添加操作
                // food 对象里的 num改变
                food.setAddNums(food.getAddNums()+1);
                // 更新一下 leftListView 和 rightView
                foodTypes.get(leftPosition).setAddNums(foodTypes.get(leftPosition).getAddNums() +1);
                updateTotalPrice(food.getFoodPrice());
            }else{

                // 删除操作
                food.setAddNums(food.getAddNums() -1);
                // 判断一下是否为0
                if(food.getAddNums() == 0){
                    // 将 food 从 购物车列表中去除
                    goodsCart.remove(position);
                }
                foodTypes.get(leftPosition).setAddNums(foodTypes.get(leftPosition).getAddNums() -1);
                updateTotalPrice(-food.getFoodPrice());
                if(goodsCart.size() == 0){
                    isVisiable = false;
                    mWindow.setVisibility(View.GONE);
                }
            }
            mRightAdapter.notifyDataSetChanged();
            mLeftAdapter.notifyDataSetChanged();
            mGoodsCartAdapter.notifyDataSetChanged();
            updateTvCount(isAdd);
        }
    };

    public void updateTotalPrice(float price){
        totalPrice += price;
        if(totalPrice <=0){
            mTotalPrice.setText("0");
        }else{
            mTotalPrice.setText(String.valueOf(totalPrice));
        }
    }

    public void updateTvCount(boolean isAdd){
        totalNum += (isAdd ? 1 : -1);
        mTvCount.setText(String.valueOf(totalNum));
        if(totalNum <=0){
            mTvCount.setVisibility(View.GONE);
        }else{
            mTvCount.setVisibility(View.VISIBLE);
        }
    }


}